
#include "linux/types.h"

// 假设bitmap为unsigned long数组，bits为位数

// 查找下一个0区域，返回起始bit索引，未找到返回bits
unsigned long bitmap_find_next_zero_area(unsigned long *bitmap, unsigned long bits, unsigned long start, unsigned long nr)
{
    unsigned long i, j;
    for (i = start; i + nr <= bits; ++i)
    {
        for (j = 0; j < nr; ++j)
        {
            if ((bitmap[(i + j) / (8 * sizeof(unsigned long))] >> ((i + j) % (8 * sizeof(unsigned long)))) & 1)
                break;
        }
        if (j == nr)
            return i;
    }
    return bits;
}

// 设置bitmap中从start开始的nr个位为1
void bitmap_set(unsigned long *bitmap, unsigned long start, unsigned long nr)
{
    unsigned long i;
    for (i = 0; i < nr; ++i)
    {
        bitmap[(start + i) / (8 * sizeof(unsigned long))] |= (1UL << ((start + i) % (8 * sizeof(unsigned long))));
    }
}

// 清除bitmap中从start开始的nr个位为0
void bitmap_clear(unsigned long *bitmap, unsigned long start, unsigned long nr)
{
    unsigned long i;
    for (i = 0; i < nr; ++i)
    {
        bitmap[(start + i) / (8 * sizeof(unsigned long))] &= ~(1UL << ((start + i) % (8 * sizeof(unsigned long))));
    }
}

// 查找下一个为1的bit，未找到返回size
unsigned long find_next_bit( unsigned long *bitmap, unsigned long size, unsigned long offset)
{
    unsigned long i;
    for (i = offset; i < size; ++i)
    {
        if ((bitmap[i / (8 * sizeof(unsigned long))] >> (i % (8 * sizeof(unsigned long)))) & 1)
            return i;
    }
    return size;
}
